package com.robcity.platform.application;

import com.robcity.platform.repo.RobotLocationInfoRepo;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
@Slf4j
@Component
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<String> {
    @Resource
    RobotLocationInfoRepo robotLocationInfoRepo;

    @Resource
    UdpClientServiceApplication udpClientServiceApplication;
    @Value("${robot.dog.ip}")
    private String robotDogIp;
    @Value("${robot.dog.port}")
    private Integer robotDogPort;
    @Value("${robot.uav.ip}")
    private String robotUavIp;
    @Value("${robot.uav.port}")
    private Integer robotUavPort;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 手动替换 Unicode 转义字符
        String decodedJson1 = StringEscapeUtils.unescapeJava(msg);
        System.out.println(ctx.channel().remoteAddress() + "," + decodedJson1);
        ctx.channel().writeAndFlush("消息已并同步到前端");

        GlobalChannelGroup.channelGroup.forEach(o -> {
            //如果端口以8089结尾，说明这个channel是web
            if (o.localAddress().toString().endsWith("8089")) {
                TextWebSocketFrame text = new TextWebSocketFrame(decodedJson1);
                o.writeAndFlush(text);
            }
        });
        // 判断是否有对应的消息
        if (decodedJson1.contains("南广场巡检开始")) {
            //给机器狗发送消息
            log.info("-----------------发送消息给机器狗:101----------------");
            udpClientServiceApplication.sendUdpMessage(" 101", robotDogIp, robotDogPort);
        }
        //给无人机发送消息
        if (decodedJson1.contains("我已经派出无人机执行监控任务")) {
            log.info("-----------------发送消息给无人机:102----------------");
            udpClientServiceApplication.sendUdpMessage(" 102", robotUavIp, robotUavPort);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + ":robot连接到server成功!");
        int size = GlobalChannelGroup.channelGroup.size();
        System.out.println("当前连接数:" + (size == 0 ? 0 : size - 1));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        GlobalChannelGroup.channelGroup.add(channel);
    }
}